package com.example.last.utils;

import cn.hutool.core.util.ObjectUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.example.last.common.Constants;
import com.example.last.common.enums.ErrorCode;
import com.example.last.common.enums.RoleEnum;
import com.example.last.entity.Account;
import com.example.last.exception.CustomException;
import com.example.last.service.AdminService;
import com.example.last.service.DoctorService;
import com.example.last.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class JwtInterceptor implements HandlerInterceptor {
    private static final Logger log = LoggerFactory.getLogger(JwtInterceptor.class);

    @Resource
    private AdminService adminService;
    @Resource
    private DoctorService doctorService;
    @Resource
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1. 从http请求的header获取token
        String token = request.getHeader(Constants.TOKEN);
        if (ObjectUtil.isNull(token)) {
            request.getParameter(Constants.TOKEN);//从参数获取一遍：/api/admin?Token=xxx&？？？
        }

        // 2. 开始执行认证
        if (ObjectUtil.isNull(token)) {
            throw new CustomException(ErrorCode.TOKEN_INVALID_ERROR);
        }

        // 获取token中的userId
        Account account = null;
        try {
            String audience = JWT.decode(token).getAudience().get(0);
            String userId = audience.split("-")[0];
            String role = audience.split("-")[1];
            // 根据用户角色判断查询用户数据
            if(RoleEnum.ADMIN.name().equals(role)) {
                account = adminService.findById(Integer.valueOf(userId));
            }
            if(RoleEnum.DOCTOR.name().equals(role)) {
                account = doctorService.findById(Integer.valueOf(userId));
            }
            if(RoleEnum.USER.name().equals(role)) {
                account = userService.findById(Integer.valueOf(userId));
            }
        } catch (Exception e) {
            ErrorCode errMsg = ErrorCode.TOKEN_CHECK_ERROR;
            log.error(errMsg + ", token=" + token, e);
            throw new CustomException(errMsg);
        }

        if (ObjectUtil.isNull(account)) {
            throw new CustomException(ErrorCode.USER_NOT_EXIST_ERROR);
        }
        try {
            // 用密码加盐验证 token
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(account.getPassword())).build();
            jwtVerifier.verify(token); // 验证token
        } catch (JWTVerificationException e) {
            throw new CustomException(ErrorCode.TOKEN_CHECK_ERROR);
        }

        log.info("token验证成功，允许放行");
        return true;

    }
}
